<template>
  <div>
    <Content title="权限" :subTitle="isNew?'新建':'编辑'" path="/permission" v-loading="loading">
      <div slot="body">
        <div style="padding-left: 20px">
          <p style="font-size: 20px">权限</p>
          <el-form :model="form" label-position="left" :rules="rules" ref="form" label-width="140px"
                   class="permission-form">
            <el-form-item label="名称" prop="name" class="my-form-item">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="编码" prop="code" class="my-form-item">
              <el-input v-model="form.code"></el-input>
            </el-form-item>
            <el-form-item label="图标" prop="icon" class="my-form-item">
              <icon v-model="form.icon" :value="form.icon" @change="iconChange"></icon>
            </el-form-item>
            <el-form-item label="父权限" prop="parent" class="my-form-item">
              <el-cascader :options="permissions"
                           change-on-select clearable
                           :props="defaultProps" v-model="form.parents"
                           @change="permissionChange"></el-cascader>
            </el-form-item>
            <el-form-item label=" 添加为权限组
              " class="my-form-item" v-show="isNew">
              <el-switch
                v-model="addPermissionGroup"
                active-text="已开启"
                inactive-text="已关闭">
              </el-switch>
              <div style="color: #6c757d;">(可快速添加一组默认的子权限,可在数据字典<span
                class="red-span"> defaut_permission_group </span>中配置)
              </div>
            </el-form-item>
            <el-form-item label="权限类型" prop="type" class="my-form-item">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option label="页面权限" :value="0"></el-option>
                <el-option label="接口权限" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="默认子权限" prop="parent" class="my-form-item" v-show="addPermissionGroup">
              <el-checkbox-group v-model="form.checkedPermissionGroup">
                <template v-for="group in defaultPermissionGroup">
                  <div>
                    <el-checkbox :label="group.key" :key="group.key">
                      <i :class="group.comment"></i><span class="permission-code-span">&nbsp;{{group.value}}&nbsp;{{form.code}}.{{group.key}}</span>
                    </el-checkbox>
                  </div>
                </template>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="排序" prop="priority" class="my-form-item">
              <el-input v-model="form.priority"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description" class="my-form-item">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Content>
    <div style="padding: 15px">
      <router-link to="/permission">
        <el-button plain round type="info" icon="el-icon-back">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="submitForm('form')" icon="el-icon-circle-check">保存</el-button>
    </div>
  </div>
</template>

<script>
  import util from '../../utils/util'
  import Content from '../../components/Content.vue'
  import Icon from '../../components/Icon.vue'
  import {mapState, mapActions} from 'vuex'
  import {showSaveResponse, validFieldExists, validateForm} from '../../utils/element-helper'
  import {Permission} from '../../utils/resource'
  import permission from "../../vuex/modules/permission";

  export default {
    name: 'permissionDetail',
    components: {
      Content,
      Icon,
    },
    data() {
      return {
        loading: false,
        isNew: true, // new true or  edit false
        initForm: {},// for edit
        defaultProps: {
          value: "id",
          label: 'name',
          children: 'children',
        },
        addPermissionGroup: false,
        type: 0,
        defaultPermissionGroup: [],
        form: {
          checkedPermissionGroup: [],
          parents: [],
          parent: 0,
          type: 0,
        },
        rules: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'},
          ],
          code: [
            {required: true, message: '编码不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          type: [
            {required: true, message: '权限类型不能为空', trigger: 'change'},
          ],
        },
      }
    },
    created() {
      this.loading = true
      let id = this.$route.params.id
      this.isNew = (id == 'new')
      this.setParent()
      if (!this.isNew) {
        //编辑
        this.loadPermission()
      } else {
        //新建
        this.loadDefaultPermissionGroup()
        this.permissionChange()
      }
      this.disableSelfPermission()
      this.loading = false
    },
    computed: {
      ...mapState("permission", [
        "permissions",
      ]),
    },
    methods: {
      async loadPermission() {
        let id = this.$route.params.id
        this.loading = false
        let res = await Permission.get(id)
        this.form = res.data
        this.form.parents = util.getTreePath(this.permissions, Number(res.data.parent))
        this.initForm = res.data
        this.$nextTick(() => {
          this.loading = false
        })
      },
      disableSelfPermission() {
        if (!this.isNew) {
          util.disableTreeNode(this.permissions, this.$route.params.id)
        }
      },
      permissionChange(data) {
        this.form.ancestors = [].concat(this.form.parents).concat(this.form.id).join(",")
        this.form.parent = this.form.parents[this.form.parents.length - 1]
      },
      setParent() {
        let parent = this.$route.params.parent
        if (!util.isNull(parent)) {
          this.form.parents = util.getTreePath(this.permissions, Number(parent))
        }
      },
      submitForm(formName) {
        return validateForm(this, formName, () => {
          showSaveResponse(this, () => {
            if (this.addPermissionGroup) {
              this.form.addedGroup = []
              for (let i = 0; i < this.form.checkedPermissionGroup.length; i++) {
                let key = this.form.checkedPermissionGroup[i]
                let permissionGroup = {
                  code: this.form.code + "." + key,
                  name: util.getText(this.defaultPermissionGroup, "key", "value", key),
                  icon: util.getText(this.defaultPermissionGroup, "key", "comment", key),
                  type: 1,
                }
                this.form.addedGroup.push(permissionGroup)
              }
            }
            return Permission.save(this.form, this.isNew ? 'post' : 'put')
          }, (res) => this.$router.back())
        })
      },
      validateExists(rule, value, callback) {
        validFieldExists(rule, value, callback, this.initForm[rule.field] != value || this.isNew, (rule, value) => Permission.exists(rule, value))
      },
      async loadDefaultPermissionGroup() {
        this.loading = false
        let res = await Permission.getDefaultPermissionGroup()
        this.defaultPermissionGroup = res.data
        let ar = []
        for (let i = 0; i < this.defaultPermissionGroup.length; i++) {
          let obj = this.defaultPermissionGroup[i]
          ar.push(obj.key)
        }
        this.form.checkedPermissionGroup = ar
        this.$nextTick(() => {
          this.loading = false
        })
      },
      iconChange(data) {
        console.log(data)
        this.form.icon = data
      },
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .permission-form {
    width: 90%;
  }

  .my-form-item {
    max-width: 700px;
  }

</style>
<style>
  .my-form-input {
    max-width: 330px;
  }

  .red-span {
    color: crimson;
  }

  .permission-code-span {
    color: #e83e8c;
  }
</style>
